package com.baocai.tools_redis.controller;

import com.baocai.tools_redis.dao.mapper.TJdItemMapper;
import com.baocai.tools_redis.modal.TJdItem;
import com.baocai.tools_redis.util.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author ：minyang
 * @date ：Created in 2019/7/23 12:34
 */
@RestController
@RequestMapping("/JdItem")
public class JdItemController {

    private static final String key = "jdItemCache_";

    @Autowired
    TJdItemMapper jdItemMapper;

    @Resource
    private RedisService redisService;

    @RequestMapping("/getJdItem")
    @ResponseBody
    public TJdItem getJdItem(long id) {
        TJdItem jdItem = jdItemMapper.selectByPrimaryKey(id);
        return jdItem;
    }

    @RequestMapping("/getJdItemCache")
    @ResponseBody
    public TJdItem getJdItemCache(long id) {

        //step1 先从redis里面取值
        TJdItem jdItem = (TJdItem) redisService.get(key + id);

        //step2 如果拿不到则从DB取值
        if (jdItem == null) {
            TJdItem jdItemDb = jdItemMapper.selectByPrimaryKey(id);
            System.out.println("fresh value from DB id:" + id);

            //step3 DB非空情况刷新redis值
            if (jdItemDb != null) {
                redisService.set(key + id, jdItemDb);
                return jdItemDb;
            }
        }
        return jdItem;
    }
}
